//
//  RefreshController.swift
//  WeiBo09
//
//  Created by 裘明 on 15/9/16.
//  Copyright © 2015年 qm. All rights reserved.
//

import UIKit

/// 向下拖拽的偏移量
private let refreshContentMaxOffset: CGFloat = -60

/// 刷新控件
class RefreshController: UIRefreshControl {
    
    /// 停止刷新
    override func endRefreshing() {
        super.endRefreshing()
        
        refreshView.endAnimation()
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        if frame.origin.y > 0 {
            return
        }
        
        // 判断是否正在刷新
        if refreshing {
            refreshView.loadingAnimation()
            return
        }
        
        if frame.origin.y < refreshContentMaxOffset && !refreshView.rotateFlag {
            refreshView.rotateFlag = true
            print("反过来")
            
        } else if frame.origin.y >= refreshContentMaxOffset && refreshView.rotateFlag {
            refreshView.rotateFlag = false
            print("转过去")
        }
    }
    
    
    // 构造函数
    override init() {
        super.init()
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init()
        
        setupUI()
    }
    
    deinit {
        // 销毁通知
        self.removeObserver(self, forKeyPath: "frame")
    }
    
    // 设置界面
    private func setupUI() {
        
        self.addObserver(self, forKeyPath: "frame", options: [], context: nil)
        tintColor = UIColor.clearColor()
        
        // 1.添加控件
        addSubview(refreshView)
        
        // 2.设置布局
        refreshView.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: refreshView.bounds.size)
    }
    
    // MARK: - 懒加载控件
    private lazy var refreshView = RefreshView.refreshView()
    
    
    
}

class RefreshView: UIView {
    
    /// 旋转标记
    private var rotateFlag = false {
        didSet {
            rotateTipAnimation()
        }
    }
    
    /// 加载图标
    @IBOutlet weak var loadingIcon: UIImageView!
    /// 提示视图
    @IBOutlet weak var tipView: UIView!
    /// 下拉图标
    @IBOutlet weak var pulldownTipIcon: UIImageView!
    
    // 从xib中加载视图
    class func refreshView() -> RefreshView {
        return NSBundle.mainBundle().loadNibNamed("RefreshView", owner: nil, options: nil).last! as! RefreshView
    }
    
    /// 旋转提示图标动画
    private func rotateTipAnimation() {
        var angle = CGFloat(M_PI)
        angle += rotateFlag ? -0.01 : +0.01
        
        UIView.animateWithDuration(0.5) {
        self.pulldownTipIcon.transform = CGAffineTransformRotate(self.pulldownTipIcon.transform, angle)
        }
    }
    /// 加载动画
    private func loadingAnimation() {
        let loadingKey = "loadingKey"
        
        if loadingIcon.layer.animationForKey(loadingKey) != nil {
            
            return
        }
        
        tipView.hidden = true
        
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 1
        
        loadingIcon.layer.addAnimation(anim, forKey: loadingKey)
    }
    
/// 停止动画
     private func endAnimation() {
        
        tipView.hidden = false
        loadingIcon.layer.removeAllAnimations()
    }
}
